﻿using FlyIL;
using FlyRemote.Base;
using System;

namespace Console1
{

    public class MyReader : IReader
    {

        public ReadGroup ReadGroup { get; set; }

        public byte[] Buffer => ReadGroup.CurrentValues;
        public ulong Base => ReadGroup.BaseAddress;
        public int RegionSize => ReadGroup.RegionSize;

        public MyReader(ReadGroup group)
        {
            this.ReadGroup = group;

            if (ReadGroup.CurrentValues == null)
                ReadGroup.ReadCurrentValues();

        }

        public bool IsOutOfModule(ulong addr)
        {
            /// 跳出到模块外
            if (addr < ReadGroup.BaseAddress || ReadGroup.EndAddress < addr)
                return true;
            return false;
        }

        public ushort? Read16(ulong addr)
        {
            if (ReadGroup.BaseAddress <= addr && addr <= ReadGroup.EndAddress - 2)
            {
                ulong offset = addr - ReadGroup.BaseAddress;
                return BitConverter.ToUInt16(ReadGroup.CurrentValues, (int)offset);

            }

            return null;
        }

        public uint? Read32(ulong addr)
        {
            if (ReadGroup.BaseAddress <= addr && addr <= ReadGroup.EndAddress - 4)
            {
                ulong offset = addr - ReadGroup.BaseAddress;
                return BitConverter.ToUInt32(ReadGroup.CurrentValues, (int)offset);

            }

            return null;
        }

        public ulong? Read64(ulong addr)
        {
            if (ReadGroup.BaseAddress <= addr && addr <= ReadGroup.EndAddress - 8)
            {
                ulong offset = addr - ReadGroup.BaseAddress;
                return BitConverter.ToUInt64(ReadGroup.CurrentValues, (int)offset);

            }

            return null;
        }

        public byte? Read8(ulong addr)
        {
            if (ReadGroup.BaseAddress <= addr && addr <= ReadGroup.EndAddress)
            {
                unchecked
                {
                    return ReadGroup.CurrentValues[addr - ReadGroup.BaseAddress];
                }
            }

            return null;

        }

        public bool IsZeroMemory(ulong addr, int size)
        {
            for (int i = 0; i < size; i++)
            {
                if (0 != ReadGroup.CurrentValues[addr - ReadGroup.BaseAddress])
                    return false;
            }

            return true;
        }
    }




}
